import { Component } from '@angular/core';
import { NavController, NavParams, ViewController, AlertController, ModalController } from 'ionic-angular';
import { DataService } from '../../services/data';
import { Storage } from '@ionic/storage';
import { AppGlobal } from '../../app/app.global';
import { RegisterPage } from '../register/register';

/*
  Generated class for the Login page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
  providers: [DataService]
})
export class LoginPage {

  email:string;
  password:string;
  canBack:boolean = true;
  constructor(public storage:Storage, 
    public navCtrl: NavController, 
    public alertCtrl: AlertController, 
    public navParams: NavParams, 
    public viewCtrl: ViewController, 
    public dataService:DataService, 
    public modalCtrl: ModalController,
  ) {
    this.canBack = navParams.get('canBack');
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }

  ionViewDidEnter(){
    console.log(AppGlobal.getInstance().isLogin, 'login');
    if (AppGlobal.getInstance().isLogin) {
      this.viewCtrl.dismiss();
    }
  }

  register(){
    let modal = this.modalCtrl.create(RegisterPage, {canBack: true});
    modal.present();
  }

  login(){
    this.dataService.login(this.email, this.password).subscribe(data => {
      console.log(data);
      if(data.code == 0){
        this.viewCtrl.dismiss();
        AppGlobal.getInstance().login(data.user);
        this.storage.set('CurrentUserInfo', JSON.stringify(data.user));
      }else{
        let alert = this.alertCtrl.create({
          title: '提示',
          subTitle: data.msg,
          buttons: [
            {
              text: 'OK',
              handler: () => {
              }
            }
          ]
        });
        alert.present();
      }
    });
  }

  dismiss() {
    this.viewCtrl.dismiss();
  }
}
